package com.heking.qlyopensdkapp.ui;

import android.Manifest;
import android.content.res.ColorStateList;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.heking.qlyopensdkapp.AppPaths;
import com.heking.qlyopensdkapp.BuildConfig;
import com.heking.qlyopensdkapp.FirmMonitor;
import com.heking.qlyopensdkapp.JsonUtils;
import com.heking.qlyopensdkapp.PageParams;
import com.heking.qlyopensdkapp.R;
import com.heking.qlyopensdkapp.SharedPreferencesUtils;
import com.heking.zplayer.qlyopen.CalendarUtil;
import com.heking.zplayer.qlyopen.Callback;
import com.heking.zplayer.qlyopen.Callback2;
import com.heking.zplayer.qlyopen.CapturePictureListener;
import com.heking.zplayer.qlyopen.IQlyPlayer;
import com.heking.zplayer.qlyopen.OnTalkListener;
import com.heking.zplayer.qlyopen.PlayError;
import com.heking.zplayer.qlyopen.PlayListener;
import com.heking.zplayer.qlyopen.QLYApi;
import com.heking.zplayer.qlyopen.QlyAccount;
import com.heking.zplayer.qlyopen.QlyCameraAbility;
import com.heking.zplayer.qlyopen.QlyCameraSetting;
import com.heking.zplayer.qlyopen.QlyPlayer;
import com.heking.zplayer.qlyopen.QlyToken;
import com.heking.zplayer.qlyopen.QlyTokenParams;
import com.heking.zplayer.qlyopen.RecordSegment;
import com.heking.zplayer.qlyopen.TimeBarView;
import com.heking.zplayer.qlyopen.UpdateTimeHelper;
import com.heking.zplayer.qlyopen.ZQlyOpenSdk;
import com.zhoug.common.utils.FileUtils;
import com.zhoug.common.utils.LogUtils;
import com.zhoug.common.utils.StringUtils;
import com.zhoug.common.utils.bundle.BundleWrap;
import com.zhoug.permissions.ZPermissions;
import com.zhoug.zmui.ZMUITopView;
import com.zhoug.zmui.date.DateSelectInterface;
import com.zhoug.zmui.dialog.date.ZMUIDateChooser;
import com.zhoug.zmui.dialog.date.ZMUIMultiDateChooser;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

/**
 * @Author: zhoug
 * @Date: 2024-11-05
 * @Description:
 */
//@Route(path = AppPaths.QlyPlayActivity)
public class QlyPlayActivity extends BaseActivity {
    private static final String TAG = ">>>QlyPlayActivity";
    private long mStartTime;
    private long mEndTime;
    private long mPendingStartTime;
    private long mPendingEndTime;

    private FirmMonitor mFirmMonitor;
    private Handler mMainHandler = new Handler(Looper.getMainLooper());
    private String mFirmId;
    private String mFirmName;
    private String mDeviceId;
    protected String cacheImage;
    private Bitmap mWatermarkBitmap;//水印
    private QlyPlayer mPlayer;

    private boolean isPlayback = false;//标记是否回放
    private boolean retry = true;
    private boolean btnPlayStatus = false;//播放按钮的状态
    private QlyCameraSetting mQlyCameraSetting;
    private QlyCameraAbility mQlyCameraAbility;
    private int colorEnableTrue;
    private int colorEnableFalse;
    private UpdateTimeHelper mUpdateTimeHelper;

    private ZMUITopView mTopView;
    private FrameLayout mContainerPlayer;
    private ImageView mIvPlace;
    private ImageView mIvWatermark;
    private ProgressBar mProgressBar;
    private ImageView mBtnPlay;
    private TextView mTvError;
    private RelativeLayout mContainerVideo;
    private ImageView mIvTalk;
    private TextView mTvTalk;
    private LinearLayout mBtnTalking;
    private ImageView mIvMute;
    private TextView mTvMute;
    private LinearLayout mBtnMute;
    private ImageView mIvHd;
    private TextView mTvHd;
    private LinearLayout mBtnHd;
    private TimeBarView mTimeBar;
    private ImageView mIvPlayBack;
    private TextView mTvPlayBack;
    private LinearLayout mBtnPlayBack;
    private TextView mTvCurrentTime;
    private TextView mBtnPlaybackTime;
    private ImageView mIvCaptureImage;
    private TextView mTvCaptureImage;
    private LinearLayout mBtnCaptureImage;


    /**
     * 设置布局文件之前执行
     *
     * @param savedInstanceState
     */
    @Override
    public void beforeLayout(@Nullable Bundle savedInstanceState) {
        BundleWrap intentExtras = getIntentExtras();
        if (null != intentExtras) {
            mFirmMonitor = intentExtras.getSerializable(PageParams.DATA, FirmMonitor.class);
            mFirmId = intentExtras.getString(PageParams.FIRM_ID);
            mFirmName = intentExtras.getString(PageParams.FIRM_NAME);
            mDeviceId = mFirmMonitor != null ? mFirmMonitor.getPlayUrl() : null;
        }
        if (StringUtils.isNullOrEmpty(mDeviceId) && BuildConfig.DEBUG) {
            mDeviceId = "xxxxS_d4430e203f3e";
        }
    }

    /**
     * 布局文件id
     *
     * @return
     */
    @Override
    public int getLayoutResID() {
        return R.layout.ativity_qly_play;
    }

    /**
     * view初始化
     */
    @Override
    public void findViews() {

        mTopView = findViewById(R.id.topView);
        mContainerPlayer = findViewById(R.id.containerPlayer);
        mIvPlace = findViewById(R.id.iv_place);
        mIvWatermark = findViewById(R.id.iv_watermark);
        mProgressBar = findViewById(R.id.progressBar);
        mBtnPlay = findViewById(R.id.btn_play);
        mTvError = findViewById(R.id.tv_error);
        mContainerVideo = findViewById(R.id.container_video);
        mIvTalk = findViewById(R.id.iv_talk);
        mTvTalk = findViewById(R.id.tv_talk);
        mBtnTalking = findViewById(R.id.btn_talking);
        mIvMute = findViewById(R.id.iv_mute);
        mTvMute = findViewById(R.id.tv_mute);
        mBtnMute = findViewById(R.id.btn_mute);
        mIvHd = findViewById(R.id.iv_hd);
        mTvHd = findViewById(R.id.tv_hd);
        mBtnHd = findViewById(R.id.btn_hd);
        mTimeBar = findViewById(R.id.time_bar);
        mIvPlayBack = findViewById(R.id.iv_playBack);
        mTvPlayBack = findViewById(R.id.tv_playBack);
        mBtnPlayBack = findViewById(R.id.btn_playBack);
        mTvCurrentTime = findViewById(R.id.tv_currentTime);
        mBtnPlaybackTime = findViewById(R.id.btn_playbackTime);
        mIvCaptureImage = findViewById(R.id.iv_captureImage);
        mTvCaptureImage = findViewById(R.id.tv_captureImage);
        mBtnCaptureImage = findViewById(R.id.btn_captureImage);
    }

    /**
     * 添加监听
     */
    @Override
    public void addListener() {
        mContainerPlayer.setOnClickListener(v -> {
            if (mBtnPlay.getVisibility() == View.VISIBLE) {
                mBtnPlay.setVisibility(View.GONE);
            } else {
                mBtnPlay.setVisibility(View.VISIBLE);
            }
        });
    }

    @Override
    public void initView() {
        colorEnableTrue = ContextCompat.getColor(this, R.color.textColor);
        colorEnableFalse = ContextCompat.getColor(this, R.color.textColorHint);
    }

    /**
     * onCreate 方法最后调用
     *
     * @param savedInstanceState
     */
    @Override
    public void onCreateEnd(@Nullable Bundle savedInstanceState) {
        if (StringUtils.isNullOrEmpty(mDeviceId)) {
            toast("没有设备id");
            finish();
            return;
        }
        mPageHelper.setTitle(mFirmName != null ? mFirmName : "对讲");
        mPendingEndTime = System.currentTimeMillis();
        mPendingStartTime = mPendingEndTime - 24 * 60 * 60 * 1000;

        initTimeBarView();

        setTalkViewStatus(false);
        mPlayer = new QlyPlayer(this);
        mPlayer.setPlayViewGroup(mContainerPlayer);
        mPlayer.setMute(false);
        setMuteViewStatus(false);
        mPlayer.setPlayUrl(mDeviceId);
        mPlayer.setAutoGetAbility(true);
        mPlayer.setAutoGetSettings(true);
        mPlayer.setPlayListener(new PlayListener() {
            @Override
            public void onPlayStatusChange(int state) {
                switch (state) {
                    case IQlyPlayer.STATE_IDLE:
                        cancelPlayLoading();
                        setPlayButtonStatus(false);
                        showWatermark(false);
                        mUpdateTimeHelper.stop();
                        Log.d(TAG, "onPlayStatusChange:IDLE");
                        break;
                    case IQlyPlayer.STATE_START:
                        showPlayLoading();
                        setPlayButtonStatus(true);
                        hideError();
                        Log.d(TAG, "onPlayStatusChange:开始播放");
                        break;
                    case IQlyPlayer.STATE_PREPARED:
                        Log.d(TAG, "onPlayStatusChange:资源准备好了");
                        break;
                    case IQlyPlayer.STATE_PLAYING:
                        hideError();
                        cancelPlayLoading();
                        setPlayButtonStatus(true);
                        setPlaceImage(false);
                        if (mBtnPlay != null) {
                            mBtnPlay.postDelayed(() -> {
                                mBtnPlay.setVisibility(View.GONE);
                            }, 2000);
                        }
                        if (isPlayback) {
                            mUpdateTimeHelper.start();
                        }
                        Log.d(TAG, "onPlayStatusChange:正在播放");
                        break;
                    case IQlyPlayer.STATE_PAUSE:
                        cancelPlayLoading();
                        setPlayButtonStatus(false);
                        Log.d(TAG, "onPlayStatusChange:暂停播放");
                        mUpdateTimeHelper.stop();
                        break;
                    case IQlyPlayer.STATE_ENDED:
                        cancelPlayLoading();
                        setPlayButtonStatus(false);
                        Log.d(TAG, "onPlayStatusChange:播放完成了");
                        mUpdateTimeHelper.stop();
                        break;

                }
            }

            @Override
            public void onPlayError(int code, String error) {
                mUpdateTimeHelper.stop();
                Log.e(TAG, "onPlayError:code=" + code + ",error=" + error);
                if (retry && code == PlayError.TOKEN_EXPIRE) {
                    Log.e(TAG, "token 过期 重新获取");
                    retry = false;
                    getOpenPlatformToken(new Callback2<Boolean>() {
                        @Override
                        public void onSuccess(Boolean success) {
                            hideError();
                            mPlayer.startPlay();
                        }

                        @Override
                        public void onError(int status, String error) {
                            showError(error);
                            cancelPlayLoading();
                            setPlayButtonStatus(false);

                        }
                    });
                } else {
                    cancelPlayLoading();
                    showError(error);
                    setPlayButtonStatus(false);
                }
            }
        });

        mPlayer.setOnCameraAbilityChange(new Callback<QlyCameraAbility>() {
            @Override
            public void onSuccess(QlyCameraAbility qlyCameraAbility) {
                Log.d(TAG, "获取设备能力成功");
                mQlyCameraAbility = qlyCameraAbility;
                if (mQlyCameraAbility != null) {
                    if (mQlyCameraAbility.supportHDVideo()) {
                        setHdEnable(true);
                    } else {
                        setHdEnable(false);
                    }
                    setHdViewStatus(mQlyCameraAbility.getHdVideo() == ZQlyOpenSdk.QUALITY_HD);
                }

            }

            @Override
            public void onError(String error) {
                Log.e(TAG, "获取设备能力失败:" + error);

            }
        });
        mPlayer.setOnQlyCameraSettingChange(new Callback<QlyCameraSetting>() {
            @Override
            public void onSuccess(QlyCameraSetting qlyCameraSetting) {
                Log.d(TAG, "获取设备设置成功:");
                mQlyCameraSetting = qlyCameraSetting;
                if (mQlyCameraSetting != null) {
                    int hdVideo = mQlyCameraSetting.getHdVideo();
                    setHdViewStatus(hdVideo == ZQlyOpenSdk.QUALITY_HD);
                }
            }

            @Override
            public void onError(String error) {
                Log.e(TAG, "获取设备设置失败:" + error);
            }
        });
        mPlayer.setCapturePictureListener(new CapturePictureListener() {
            @Override
            public void onCapturePictureResult(boolean success, String path) {
                if (success) {
                    toast("截屏成功:" + path);
                } else {
                    toast("截屏失败");
                }
            }
        });
        //回放直播
        mBtnPlayBack.setOnClickListener(v -> {
            if (isPlayback) {
                setPlayBack(false);
                mPlayer.switchToLive();
            } else {
                RecordSegment startRecordSegment = mTimeBar.getStartRecordSegment();
                if (startRecordSegment != null) {
                    playBack(startRecordSegment.getBeginTimeMillis());
                } else {
                    getTimelineSectionList();
                }
            }

        });
        //选择回放时间
        mBtnPlaybackTime.setOnClickListener(v -> {
            ZMUIMultiDateChooser chooser = new ZMUIMultiDateChooser(this);
            chooser.setStartTime(CalendarUtil.timeToyyyy_MM_dd_HH_mm(mStartTime));
            chooser.setEndTime(CalendarUtil.timeToyyyy_MM_dd_HH_mm(mEndTime));
            chooser.setDateMode(ZMUIMultiDateChooser.MODE_DATE_TIME);
            chooser.setOrientation(DateSelectInterface.HORIZONTAL);
            chooser.setCallback(new ZMUIMultiDateChooser.Callback() {
                @Override
                public void onSelectDate(String startTime, String endTime) {
                    mBtnPlaybackTime.setText(StringUtils.format("%s 至 %s", startTime, endTime));
                    mPendingStartTime = CalendarUtil.yyyy_MM_dd_HH_mmToLong(startTime);
                    mPendingEndTime = CalendarUtil.yyyy_MM_dd_HH_mmToLong(endTime);
                    mTimeBar.setFileInfoList(null);
                    mStartTime = 0;
                    mEndTime = 0;
                    getTimelineSectionList();
                }
            });
            chooser.show();
        });


        mPlayer.setOnTalkListener(new OnTalkListener() {
            @Override
            public void onTalkCallback(int status, String error) {
                toast(error);
            }
        });

        mBtnPlay.setOnClickListener(v -> {
            if (mPlayer != null) {
                if (btnPlayStatus) {
                    setPlayButtonStatus(false);
                    mPlayer.stopPlay();
                } else {
                    hideError();
                    setPlayButtonStatus(true);
                    mPlayer.startPlay();
                }
            }

        });
        mBtnCaptureImage.setOnClickListener(v -> {
            ZPermissions.with(this)
                    .setPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.READ_EXTERNAL_STORAGE)
                    .setDescription("截屏需要存储权限")
                    .setCallback((success, granted, denied) -> {
                        if (success) {
                            File externalPublicFolder = FileUtils.getExternalPublicFolder(Environment.DIRECTORY_PICTURES);
                            File file = new File(externalPublicFolder.getAbsolutePath(), System.currentTimeMillis() + ".png");
                            if (!file.exists()) {
                                try {
                                    file.createNewFile();
                                } catch (IOException e) {
                                    toast(e.getMessage());
                                    return;
                                }
                            }
                            mPlayer.capturePicture(file.getAbsolutePath());
                        }
                    })
                    .request();


        });
        //对讲
        mBtnTalking.setOnClickListener(v -> {
            if (!mPlayer.isPlaying()) {
                toast("视频没有播放");
                return;
            }

            if (mPlayer.isTalking()) {
                setTalkViewStatus(false);
                mPlayer.stopVoiceTalk();
            } else {
                if (mPlayer.isMute()) {
                    mPlayer.setMute(false);
                    setMuteViewStatus(false);
                }
                setTalkViewStatus(true);
                mPlayer.startVoiceTalk();
            }
        });
        //设置静音
        mBtnMute.setOnClickListener(v -> {
            boolean mute = !mPlayer.isMute();
            mPlayer.setMute(mute);
            setMuteViewStatus(mute);
        });
        //切换清晰度
        mBtnHd.setOnClickListener(v -> {
            if (mQlyCameraSetting == null) return;
            mPlayer.switchPlayQuality(new Callback<Integer>() {
                @Override
                public void onSuccess(Integer integer) {
                    if (integer != -1) {
                        setHdViewStatus(integer == ZQlyOpenSdk.QUALITY_HD);
                    }
                }

                @Override
                public void onError(String error) {
                    toast(error);
                }
            });
        });

        setPlaceImage(true);
        showPlayLoading();
        getOpenPlatformToken(new Callback2<Boolean>() {
            @Override
            public void onSuccess(Boolean qlyToken) {
                mPlayer.startPlay();

            }

            @Override
            public void onError(int status,String error) {
                if(status==PlayError.TOKEN_EXPIRE){
                    SharedPreferencesUtils.setMonitorToken(mDeviceId,null);
                    toast("重新获取token");
                    getTokenFromServer(new Callback2<Boolean>() {
                        @Override
                        public void onSuccess(Boolean aBoolean) {
                            mPlayer.startPlay();
                        }

                        @Override
                        public void onError(int status, String error) {
                            Log.e(TAG, "获取token失败:" + error);

                        }
                    });
                }else{
                    cancelPlayLoading();
                    Log.e(TAG, "获取token失败:" + error);
                    toast(error);
                }

            }
        });
        setTalkEnable(true);
        setHdEnable(false);
        mUpdateTimeHelper = new UpdateTimeHelper(mTimeBar, mPlayer);
        mUpdateTimeHelper.setonUpdateTimeListener(new UpdateTimeHelper.OnUpdateTimeListener() {
            @Override
            public void onUpdateTime(long currentTime) {
                String currentTimeStr = CalendarUtil.timeToyyyy_MM_dd_HH_mm_ss(currentTime);
                Log.d(TAG, "onUpdateTime:" + currentTimeStr);
                mTvCurrentTime.setText(currentTimeStr);
            }
        });
        setPlayBack(false);
    }

    private void getTimelineSectionList() {
        getTimelineSectionList(0);
    }

    /**
     * 获取云存储回放数据列表
     */
    private void getTimelineSectionList(long pendingPlayTime) {
        if (!(mPendingStartTime > 0 && mPendingEndTime > 0 && mPendingEndTime > mPendingStartTime)) {
            Log.d(TAG, "getTimelineSectionList:开始时间结束时间错误:" + mPendingStartTime + " - " + mPendingStartTime);
            return;
        }
        Log.d(TAG, "获取云存储回放数据列表:" + CalendarUtil.timeToyyyy_MM_dd_HH_mm_ss(mPendingStartTime) + " 至 " + CalendarUtil.timeToyyyy_MM_dd_HH_mm_ss(mPendingEndTime));
        mPlayer.getTimelineSectionList(mPendingStartTime, mPendingEndTime, new Callback<List<RecordSegment>>() {
            @Override
            public void onSuccess(List<RecordSegment> recordSegments) {
                Log.d(TAG, "获取云存储回放数据列表成功:" + recordSegments.size() + "");
               /* for (RecordSegment item :recordSegments ) {
                    Log.d(TAG, "onSuccess:"+item.getBeginTime()+" 至 "+item.getEndTime());
                }*/
                //有回放片段
                if (!recordSegments.isEmpty()) {
                    List<RecordSegment> newRecordSegmentList = mTimeBar.getRecordSegmentList();
                    if (!newRecordSegmentList.isEmpty()) {
                        List<RecordSegment> all = new ArrayList<>(newRecordSegmentList);
                        all.addAll(recordSegments);
                        Collections.sort(all);
                        mTimeBar.setFileInfoList(all);
                        if (mPendingStartTime < mStartTime) {
                            mStartTime = mPendingStartTime;
                        }
                        if (mPendingEndTime > mEndTime) {
                            mEndTime = mPendingEndTime;
                        }
                    } else {
                        mStartTime = mPendingStartTime;
                        mEndTime = mPendingEndTime;
                        mTimeBar.setFileInfoList(recordSegments);
                    }
                    mBtnPlaybackTime.setText(StringUtils.format("%s 至 %s",
                            CalendarUtil.timeToyyyy_MM_dd_HH_mm(mStartTime),
                            CalendarUtil.timeToyyyy_MM_dd_HH_mm(mEndTime)));

                    if (pendingPlayTime > 0) {
                        if (mTimeBar.isInFileInfoList(pendingPlayTime)) {
                            playBack(pendingPlayTime);
                        }
                    } else {
                        RecordSegment startRecordSegment = mTimeBar.getStartRecordSegment();
                        if (startRecordSegment != null) {
                            playBack(startRecordSegment.getBeginTimeMillis());
                        }
                    }


                } else {
                    toast("选择的时间段没有录像片段");
                }

            }

            @Override
            public void onError(String error) {
                Log.e(TAG, "获取云存储回放数据列表失败:" + error);
            }
        });
    }

    /**
     * 初始化时间选择器
     */
    private void initTimeBarView() {
        mTimeBar.setTimeBarCallback(new TimeBarView.SimpleTimePickedCallBack() {

            @Override
            public void onTimePickedCallback(long currentTime, boolean inFileInfoList) {
                if (isPlayback) {
                    if (inFileInfoList) {
                        playBack(currentTime);
                    } else {
                        //时间没有在片段时间内
                        //如果超出获取回放的起止时间则获取播放片段
                        if (currentTime < mStartTime) {
                            //左移
                            mPendingEndTime = mStartTime;
                            mPendingStartTime = mPendingEndTime - 24 * 60 * 60 * 1000;
                            getTimelineSectionList(currentTime);
                        } else if (currentTime > mEndTime) {
                            //右移
                            mPendingStartTime = mEndTime;
                            mPendingEndTime = mPendingStartTime + 24 * 60 * 60 * 1000;
                            long currentTimeMillis = System.currentTimeMillis();
                            if (mPendingEndTime > currentTimeMillis) {
                                mPendingEndTime = currentTimeMillis;
                            }
                            getTimelineSectionList(currentTime);
                        } else {
                            toast("当前时间没有录像片段");
                        }
                    }
                }

            }

            @Override
            public void onTimePickedCallback(long currentTime) {

            }
        });

    }

    /**
     * 回放
     *
     * @param currentTime
     */
    private void playBack(long currentTime) {
        showPlayLoading();
        if (!isPlayback) {
            setPlayBack(true);
        }
        mUpdateTimeHelper.stop();
        Log.d(TAG, "playBack:" + CalendarUtil.timeToyyyy_MM_dd_HH_mm_ss(currentTime));
        mPlayer.seek(currentTime);
    }

    /**
     * 设置对讲状态
     *
     * @param talking
     */
    private void setTalkViewStatus(boolean talking) {
        if (talking) {
            mIvTalk.setImageResource(R.drawable.voice_call_on);
            mTvTalk.setText("正在对讲");
        } else {
            mIvTalk.setImageResource(R.drawable.voice_call_off);
            mTvTalk.setText("语音对讲");
        }
    }

    /**
     * 设置对讲状态
     *
     * @param enable
     */
    private void setTalkEnable(boolean enable) {

        if (enable) {
            mTvTalk.setTextColor(colorEnableTrue);
            mIvTalk.setImageTintList(null);
            mBtnTalking.setClickable(true);
        } else {
            mIvTalk.setImageResource(R.drawable.voice_call_off);
            mTvTalk.setText("语音对讲");
            mTvTalk.setTextColor(colorEnableFalse);
            mIvTalk.setImageTintList(ColorStateList.valueOf(colorEnableFalse));
            mBtnTalking.setClickable(false);
        }
    }


    /**
     * 设置静音状态
     *
     * @param mute
     */
    private void setMuteViewStatus(boolean mute) {
        if (mute) {
            mIvMute.setImageResource(R.drawable.play_mute_start);
        } else {
            mIvMute.setImageResource(R.drawable.play_mute_stop);
        }
    }

    /**
     * 设置高清标清状态
     *
     * @param hd
     */
    private void setHdViewStatus(boolean hd) {
        if (hd) {
            mIvHd.setImageResource(R.drawable.player_quary_hd);
            mTvHd.setText("高清");
        } else {
            mIvHd.setImageResource(R.drawable.player_quary_sd);
            mTvHd.setText("标清");
        }
    }

    /**
     * 设置对讲状态
     *
     * @param enable
     */
    private void setHdEnable(boolean enable) {
        if (enable) {
            mTvHd.setTextColor(colorEnableTrue);
            mIvHd.setImageTintList(null);
            mBtnHd.setClickable(true);
        } else {
            mTvHd.setTextColor(colorEnableFalse);
            mIvHd.setImageTintList(ColorStateList.valueOf(colorEnableFalse));
            mBtnHd.setClickable(false);
        }
    }

    /**
     * 获取token
     *
     * @param callback
     */
    private void getOpenPlatformToken(Callback2<Boolean> callback) {
        QlyToken qlyToken = SharedPreferencesUtils.getMonitorToken(mDeviceId);
        if (qlyToken != null && !qlyToken.isExpired()) {
            ZQlyOpenSdk.setOpenPlatformToken1(qlyToken.getToken(), callback);
            return;
        }
        getTokenFromServer(callback);
    }

    private void getTokenFromServer(Callback2<Boolean> callback){
        Log.d(TAG, "获取token");
        QlyTokenParams params = new QlyTokenParams();
        params.setAppId(QlyAccount.appId);
        params.setSecret(QlyAccount.secret);
        params.setOperatorType(ZQlyOpenSdk.TOKEN_OPERATOR_TYPE_CUSTOM);
        params.setTargetType(ZQlyOpenSdk.TARGET_TYPE_DEVICE);
        params.setTarget(mDeviceId);
        params.setAction(ZQlyOpenSdk.ACTION_WRITE);

        QLYApi.getOpenPlatformToken(params, new Callback<QlyToken>() {
            @Override
            public void onSuccess(QlyToken qlyToken) {
                LogUtils.d(TAG, "获取设备token成功:");
                SharedPreferencesUtils.setMonitorToken(mDeviceId, qlyToken);
                ZQlyOpenSdk.setOpenPlatformToken1(qlyToken.getToken(), callback);
            }

            @Override
            public void onError(String error) {
                LogUtils.e(TAG, "获取设备token失败:" + error);
                if (callback != null) {
                    callback.onError(0, error);
                } else {
                    showError(error);
                }
            }
        });
    }


    /**
     * 显示错误信息
     *
     * @param error
     */
    protected void showError(String error) {
        if (mTvError == null) {
            return;
        }
        if (error == null) {
            mTvError.setText("");
            mTvError.setVisibility(View.GONE);
        } else {
            mTvError.setText(error);
            mTvError.setVisibility(View.VISIBLE);
        }
    }

    protected void hideError() {
        if (mTvError != null) {
            mTvError.setText("");
            mTvError.setVisibility(View.GONE);
        }
    }

    /**
     * 改变播放按钮状态
     *
     * @param btnPlayStatus 是否在播放
     */
    protected void setPlayButtonStatus(boolean btnPlayStatus) {
        if (mBtnPlay == null) return;
        if (btnPlayStatus) {
            mBtnPlay.setImageResource(R.drawable.icon_monitor_stop);
        } else {
            mBtnPlay.setImageResource(R.drawable.icon_monitor_play);
        }
        this.btnPlayStatus = btnPlayStatus;
    }


    /**
     * 显示视频加载框
     */
    protected void showPlayLoading() {
        if (mProgressBar != null) {
            mProgressBar.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 隐藏视频加载框
     */
    protected void cancelPlayLoading() {
        if (mProgressBar != null) {
            mProgressBar.setVisibility(View.GONE);
        }
    }

    /**
     * 设置占位图
     *
     * @param visibility
     */
    protected void setPlaceImage(boolean visibility) {
        /*try {
            if (visibility && mIvPlace != null) {
                mIvPlace.setVisibility(View.VISIBLE);
                //占位图为空时使用企业图片
                String imageUrl = null;
                if (StringUtils.isNullOrEmpty(imageUrl)) {
                    FirmInfo en_firmInfo = LoginUserLiveData.getFirmInfo();
                    if (en_firmInfo != null) {
                        imageUrl = en_firmInfo.getFirmImage();
                    }
                }
                if (imageUrl != null && !"".equals(imageUrl)) {
//                    ZImageLoader.load(getActivity(), mIvPlace, ComFileUtils.getRealUrl(imageUrl), R.drawable.monitor_image_default, R.drawable.monitor_image_default, null);
                    MyImageLoader.with(getActivity())
                            .load(imageUrl)
                            .placeholder(R.drawable.monitor_image_default)
                            .error(R.drawable.monitor_image_default)
                            .into(mIvPlace);
                } else {
                    //没有占位图
                    if (imageExists(cacheImage)) {
                        //加载缓存的截屏图片
//                        ZImageLoader.load(getActivity(), mIvPlace, cacheImage);
                        MyImageLoader.with(getActivity())
                                .placeholder(R.drawable.monitor_image_default)
                                .error(R.drawable.monitor_image_default)
                                .load(cacheImage)
                                .into(mIvPlace);
                    } else {
                        //加载默认图片
//                        ZImageLoader.load(getActivity(), mIvPlace, R.drawable.monitor_image_default);
                        MyImageLoader.with(getActivity())
                                .load(R.drawable.monitor_image_default)
                                .into(mIvPlace);
                    }
                }
            } else if (mIvPlace != null) {
                mIvPlace.setVisibility(View.GONE);
            }
        } catch (Exception e) {
        }
        if (visibility) {
            showWatermark(false);
        } else {
            showWatermark(true);
        }*/
    }

    protected boolean imageExists(String path) {
        if (path != null) {
            File file = new File(path);
            if (file.exists() && file.length() > 0) {
                return true;
            }
        }
        return false;
    }


    /**
     * 显示/隐藏视频水印
     *
     * @param show
     */
    protected void showWatermark(boolean show) {
        /*if (mIvWatermark == null) {
            return;
        }
        if (show) {
            if (mWatermarkBitmap == null) {
                mWatermarkBitmap = WatermarkUtils.createWatermarkBitmap();
            }
            if (mWatermarkBitmap != null) {
                mIvWatermark.setImageBitmap(mWatermarkBitmap);
                setWatermarkVisibility(true);
            } else {
                setWatermarkVisibility(false);
            }
        } else {
            setWatermarkVisibility(false);
        }*/
    }

    /**
     * 设置水印的显示状态
     *
     * @param show
     */
    private void setWatermarkVisibility(boolean show) {
        if (mIvWatermark != null) {
            mIvWatermark.setVisibility(show ? View.VISIBLE : View.GONE);
        }
    }

    private void setPlayBack(boolean playback) {
        if (isPlayback != playback) {
            isPlayback = playback;
            if (isPlayback) {
                mTvPlayBack.setText("直播");
                mTvCurrentTime.setVisibility(View.VISIBLE);
                mUpdateTimeHelper.stop();
            } else {
                mTvPlayBack.setText("回放");
                mTvCurrentTime.setVisibility(View.GONE);
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPlayer != null) {
            mPlayer.release();
        }
        if (mUpdateTimeHelper != null) {
            mUpdateTimeHelper.stop();
        }
    }

}
